package chagine.core.util;

import chagine.core.ErrorCode;
import chagine.core.exception.SeeingRuntimeException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;

import java.util.ArrayList;
import java.util.List;
import java.util.function.BiPredicate;
import java.util.function.Predicate;

@Slf4j
public class CopyUtil {

    private static final ObjectMapper om = new ObjectMapper();

    /**
     * 复制Bean
     */
    public static <T, V> V copyBean(T source, Class<V> vClass) {
        try {
            V target = vClass.newInstance();
            BeanUtils.copyProperties(source, target);
            return target;
        }   catch (InstantiationException|IllegalAccessException e){
            log.error("copy list error >>>", e);
            throw new SeeingRuntimeException(ErrorCode.BUSINESS_EXCEPTION, "new instance error!");
        }
        catch (BeansException e){
            log.error("copy list error >>>", e);
            throw new SeeingRuntimeException(ErrorCode.BUSINESS_EXCEPTION, "copy list error!");
        }
        catch (Exception e) {
            log.error("post process error>>>", e);
            throw new RuntimeException(e);
        }
    }

    public static <T, V> List<V> copyList(List<T> sourceList, Class<V> vClass) {
        List<V> targetList = new ArrayList<>();
        for (T source : sourceList) {
            try {
                V target = vClass.newInstance();
                BeanUtils.copyProperties(source, target);
                targetList.add(target);
            }
            catch (InstantiationException|IllegalAccessException e){
                log.error("copy list error >>>", e);
                throw new SeeingRuntimeException(ErrorCode.BUSINESS_EXCEPTION, "new instance error!");
            }
            catch (BeansException e){
                log.error("copy list error >>>", e);
                throw new SeeingRuntimeException(ErrorCode.BUSINESS_EXCEPTION, "copy list error!");
            }
            catch (Exception e) {
                log.error("before or after process error>>>", e);
                throw new RuntimeException(e);
            }
        }
        return targetList;
    }
}
